﻿using KwaiXiaoDian.Dao;
using KwaiXiaoDian.Data;
using KwaiXiaoDian.IService;
using KwaiXiaoDian.Service;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using KwaiXiaoDian.Entity.DO;
using SSharing.Frameworks.NetCore.Common.Extends;
using System.Linq.Expressions;
using KwaiXiaoDian.Entity.Common;
using KwaiXiaoDian.Entity.VO.User;

namespace KwaiXiaoDian.Tool
{
    public partial class CookieFrm : Form
    {
        IConfigurationRoot _configuration;
        IServiceProvider _serviceProvider;
        public static Logger _logger = LogManager.GetCurrentClassLogger();

        public CookieFrm()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;//fix从不是创建控件的线程访问它

            try
            {
                _configuration = CreateConfigurationRoot();
                _serviceProvider = CreateServiceProvider();
            }
            catch (Exception ex)
            {
                _logger.Error(ex, string.Format("BasicDataFrm实例化时发生异常，message:{0}", ex.Message));
            }
        }

        /// <summary>
        /// 创建DI容器
        /// </summary>
        /// <returns></returns>
        IServiceProvider CreateServiceProvider()
        {
            IServiceCollection serviceCollection = new ServiceCollection();
            serviceCollection
                .AddSingleton<IConfiguration>(_configuration)
                .AddLogging(builder =>
                {
                    builder.ClearProviders();
                    builder.AddConfiguration(_configuration.GetSection("Logging"));
                    builder.AddConsole();
                    builder.AddNLog();
                })
                .AddDbContext<KwaiXiaoDianDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("KwaiXiaoDianDB")))
                .AddServices(_configuration)
                .AddDaos()
                .AddMemoryCache()
                .AddHttpClient();

            return serviceCollection.BuildServiceProvider();
        }

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <returns></returns>
        IConfigurationRoot CreateConfigurationRoot()
        {
            IConfigurationBuilder builder = new ConfigurationBuilder();
            builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
            return builder.Build();
        }

        #region Cookie管理
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click_1(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要保存吗？", "保存Cookie信息", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                button1.Enabled = false;
                var domain = this.textBox1.Text;
                var cookie = this.textBox2.Text;
                var now = DateTime.Now;
                if (domain.IsNullOrEmpty() || cookie.IsNullOrEmpty())
                {
                    MessageBox.Show("域名和Cookie不能为空.");
                    button1.Enabled = true;
                    return;
                }

                //Cookie字符串格式处理
                Dictionary<string, string> dic = new Dictionary<string, string>();
                var arr1 = cookie.Split(";", StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in arr1)
                {
                    var arr2 = item.Split("=", StringSplitOptions.None);
                    var name = arr2[0].Trim();
                    var value = arr2[1];
                    dic.Add(name, value);
                }

                //保存，先全删再新增
                var addSuccess = false;
                domain = domain.Trim();
                using (var scope = _serviceProvider.CreateScope())
                {
                    var cookieService = scope.ServiceProvider.GetService<ICookieService>();
                    var removeSuccess = cookieService.Remove(p => p.Domain == domain);
                    foreach (var item in dic)
                    {
                        addSuccess = cookieService.Add(new TCookie
                        {
                            CreatedBy = -1,
                            CreatedTime = now,
                            LastUpdatedBy = -1,
                            LastUpdatedTime = now,
                            Domain = domain,
                            Name = item.Key,
                            Value = item.Value
                        });
                    }
                }
                if (addSuccess)
                {
                    MessageBox.Show("OK");
                }
                button1.Enabled = true;
            }
        }



        #endregion

        #region 用户管理

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要新增吗？", "新增用户", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                button2.Enabled = false;
                var now = DateTime.Now;
                var phoneNumber = this.textBox3.Text;
                var nickName = this.textBox4.Text;
                var isAdmin = this.radioButton1.Checked;
                var isUser = this.radioButton2.Checked;

                //输入校验
                if (phoneNumber.IsNullOrEmpty())
                {
                    MessageBox.Show("登录手机不能为空！");
                    button2.Enabled = true;
                    return;
                }

                //角色处理
                var role = Enums.RoleType.TENANT.ToString();
                if (isAdmin)
                {
                    role = Enums.RoleType.ADMIN.ToString();
                }

                //新增，先检查用户是否存在，不存在则新增
                var addSuccess = false;
                using (var scope = _serviceProvider.CreateScope())
                {
                    var userService = scope.ServiceProvider.GetService<IUserService>();
                    var addResult = userService.Add(new AddUserRequest
                    {
                        PhoneNumber = phoneNumber,
                        NickName = nickName,
                        Role = role
                    });
                    if (addResult.Item1 != true)
                    {
                        MessageBox.Show(addResult.Item2);
                        button2.Enabled = true;
                        return;
                    }

                    addSuccess = addResult.Item1;
                }
                if (addSuccess)
                {
                    MessageBox.Show("OK");

                    this.textBox3.Text = "";
                    this.textBox4.Text = "";
                }
                button2.Enabled = true;
            }
        }
        #endregion

        private void button3_Click(object sender, EventArgs e)
        {
            //初始化全部商品类别默认为首页
            if (MessageBox.Show("确定要初始化全部商品类别吗？", "商品类别", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                button3.Enabled = false;
                var initSuccess = false;
                using (var scope = _serviceProvider.CreateScope())
                {
                    var productService = scope.ServiceProvider.GetService<IProductService>();
                    var initProductChannelResult = productService.InitProductChannel();
                    if (initProductChannelResult.Item1 != true)
                    {
                        MessageBox.Show(initProductChannelResult.Item2);
                        button3.Enabled = true;
                        return;
                    }
                    initSuccess = initProductChannelResult.Item1;
                }
                if (initSuccess)
                {
                    MessageBox.Show("OK");
                }
                button3.Enabled = true;
            }
        }
    }
}
